﻿// ***********************************************************************
// Assembly         : INNOVACALL.Framework.Common
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="TokenizedAuthorizeAttribute.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;

namespace INNOVACALL.Framework.Common.MVCHelpers
{
    /// <summary>
    /// A custom version of the <see cref="AuthorizeAttribute" /> that supports working
    /// around a cookie/session bug in Flash.
    /// </summary>
    /// <remarks>Details of the bug and workaround can be found on this blog:
    /// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx</remarks>
    public class TokenizedAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The key to the authentication token that should be submitted somewhere in the request.
        /// </summary>
        private const string TOKEN_KEY = "AuthenticationToken";

        /// <summary>
        /// This changes the behavior of AuthorizeCore so that it will only authorize
        /// users if a valid token is submitted with the request.
        /// </summary>
        /// <param name="httpContext">Contexte HTTP qui encapsule toutes les informations spécifiques à HTTP concernant une requête HTTP individuelle.</param>
        /// <returns>true si l'utilisateur est autorisé ; sinon, false.</returns>
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            string token = httpContext.Request.Params[TOKEN_KEY];

            if (token != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

                if (ticket != null)
                {
                    FormsIdentity identity = new FormsIdentity(ticket);
                    string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
                    GenericPrincipal principal = new GenericPrincipal(identity, roles);
                    httpContext.User = principal;
                }
            }

            return base.AuthorizeCore(httpContext);
        }
    }
}
